﻿using System;
using K9Nano.Authentication;
using K9Nano.Authorization;
using K9Nano.Domain;
using K9Nano.EFCore;
using K9Nano.Organization;
using Microsoft.EntityFrameworkCore;

namespace K9Nano.Admin.Data
{
    public class K9AdminDbContext<TUser, TRole> : K9IdentityDbContext<TUser, TRole, Guid>
        where TUser : User, IMayHaveTenant
        where TRole : Role, IMayHaveTenant
    {
        public K9AdminDbContext(DbContextOptions options, IDbContextHelper helper) : base(options, helper)
        {
        }

        public virtual DbSet<UserBlacklist> UserBlacklists { get; set; }

        public virtual DbSet<OrganizationUnit> OrganizationUnits { get; set; }

        public virtual DbSet<UserWeixinLogin> UserWeixinLogins { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var uerWeixinLogin = modelBuilder.Entity<UserWeixinLogin>();
            uerWeixinLogin.HasIndex(x => new
                {
                    x.ClientId,
                    x.AppId,
                    x.OpenId,
                    x.UnionId
                })
                .HasName("idx_app_user");
            uerWeixinLogin.HasIndex(x => x.UserId).HasName("idx_user_login");

            modelBuilder.Entity<UserBlacklist>()
                .HasIndex(x => x.User)
                .HasName("idx_user");

            var role = modelBuilder.Entity<Role>();
            role.HasIndex(x => new {x.TenantId, x.Api});
        }
    }
}